﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SoundEdge.Common;
using System.ComponentModel.Composition;
using System.Xml.Serialization;

namespace SoundEdge.Media.Settings
{
    [Serializable,
    XmlInclude(typeof(AsioOutSettings)),
    XmlInclude(typeof(DirectSoundOutSettings)),
    XmlInclude(typeof(WasapiOutSettings)),
    XmlInclude(typeof(WaveOutSettings)),
    Export]
    public class OutputSettings : IOutputSettings
    {
        public int Latency { get; set; }

        public string DeviceName { get; set; }

        public void SaveSettings(string fileName)
        {
            File.WriteAllText(fileName, XmlSerialization.ToXML(this));
        }

        public static T LoadSettings<T>(string fileName) where T : IOutputSettings
        {
            if (!File.Exists(fileName))
            {
                return default(T);
            }

            try
            {
                return (T)XmlSerialization.FromXML(File.ReadAllText(fileName), typeof(OutputSettings));
            }
            catch
            {
                return default(T);
            }
        }

        public static IOutputSettings LoadSettings(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return null;
            }

            try
            {
                return XmlSerialization.FromXML(File.ReadAllText(fileName), typeof(OutputSettings)) as IOutputSettings;
            }
            catch
            {
                return null;
            }
        }

        public IOutputDevicePlugin GetPlugin(IEnumerable<IOutputDevicePlugin> outputPlugins)
        {
            if (outputPlugins == null)
            {
                return null;
            }
            return outputPlugins.FirstOrDefault(item => item.Name == DeviceName);
        }
    }
}
